package com.cardone.platform.common.support;

import com.cardone.common.service.SimpleDefaultService;
import com.cardone.context.ContextHolder;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.support.TaskUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.Map.Entry;

/**
 * 初始化数据支持
 *
 * @author yaohaitao
 */
@Getter
@Setter
@Slf4j
public class InitDataSupport {

    /**
     * 是否初始化数据
     */
    private Boolean initData;

    /**
     * 异步调用
     */
    private TaskExecutor taskExecutor;

    /**
     * 初始化
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void init() {
        if (this.taskExecutor == null) {
            return;
        }

        this.taskExecutor.execute(TaskUtils.decorateTaskWithErrorHandler(() -> {
            try {
                Thread.sleep(9000);
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }

            com.cardone.common.cache.util.CacheUtils.flush();

            if (BooleanUtils.isNotTrue(this.initData)) {
                return;
            }

            Map<String, SimpleDefaultService> simpleDefaultServiceMap = ContextHolder.getApplicationContext().getBeansOfType(SimpleDefaultService.class);

            if (MapUtils.isEmpty(simpleDefaultServiceMap)) {
                return;
            }

            for (Entry<String, SimpleDefaultService> simpleDefaultServiceEntry : simpleDefaultServiceMap.entrySet()) {
                try {
                    simpleDefaultServiceEntry.getValue().init();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }

            com.cardone.common.cache.util.CacheUtils.flush();
        }, null, true));
    }
}
